//
//  BSSetingViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/4/7.
//  Copyright © 2016年 Ym. All rights reserved.
//

#import "ZipArchive.h"

#import "BSPasswordSettingViewController.h"
#import "BSAddFanmilyViewController.h"
#import "BSBluetootnAndBatteryView.h"
#import "BSSettingTableViewCell.h"
#import "BSSetingViewController.h"
#import "BSMyInfoViewController.h"
#import "BSOptionAndDeviceInfoViewController.h"

#import "BSUIDeviceResponseList+BSUIDeviceResponseList_category.h"

#import "StringResponse.h"

@interface BSSetingViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) BSBluetootnAndBatteryView *headView;
@property (nonatomic, strong) UIView  *NCview, *passDataNoteView;
//剩余上传文件数量
@property (nonatomic, strong) UILabel *passdataLable;

//解除设备 提示框
@property (nonatomic, strong) UIView *freeLableView;
@property (nonatomic, strong) UITextField *freeTextfeild;

//解除绑定用的UUID
@property (nonatomic, strong) NSString *uuidString;

@property (nonatomic, assign) BOOL isUploading;

@property (nonatomic, strong) UILabel *lableUploadNote;

//总共要上传的文件数
@property (nonatomic, assign) int  numberOffiles;

@property (nonatomic, strong) UIButton *uploadButton;

@end

@implementation BSSetingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _NCview = [[UIView alloc]initWithFrame:self.view.bounds];
    _NCview.backgroundColor = BSBackViewColor;
    _NCview.alpha = 0.5;
    _isUploading = NO;
    
    [self addHeadView];
    self.view.backgroundColor = [UIColor colorWithRed:235/255.0 green:236/255.0 blue:237/255.0 alpha:1];

    
//    检测蓝牙信号
//    [self observeRSSI];
    
#pragma mark  获取绑定设备的UUID
    
    [self getBindUUID];
    
}

- (void)getBindUUID{


    [PKRequestManager GetUserDeviceWithuserID:[BSUserSGton userHandle].user_id method:POST finish:^(NSData *data) {
        //            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        BSUIDeviceResponseList *model = [[BSUIDeviceResponseList alloc]init];
        
        [model dealWithData:data];
        
        if ([model.Code isEqualToString:@"0"]) {
            self.uuidString = model.DeviceModel.UUID;
            //                有这个UUID 就可以 接收验证码
            [BSBluetoothSingleton shareBlutooth].uuiduuid = model.DeviceModel.UUID;
        } else {
            [PKRequestManager showAlertView:model.Message];
        }
        
        ;
    } string:NetStr error:^(NSError *error) {
        ;
    }];

}

- (void)observeRSSI{

    [[BSBluetoothSingleton shareBlutooth] addObserver:self forKeyPath:@"RSSIValue" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil]; ;

}
//  键值发生变化 会触发的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //哪一个属性发生的变化
    NSLog(@"%@",keyPath);
    //这个属性时属于谁的
    NSLog(@"%@",object);
    //change 值的变化
    NSLog(@"%@",change);
    //context 携带的参数
    NSLog(@"%@",context);
    //移除观察者
    [object removeObserver:self forKeyPath:keyPath context:context];
}


- (void)addHeadView{
    self.headView = [[BSBluetootnAndBatteryView alloc]initWithFrame:CGRectMake(0, 0, kScrenWidth, kScrenHeight)];
    
    [self.headView.backBT addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
//    一键上传
    [self.headView.passBT addTarget:self action:@selector(passData) forControlEvents:(UIControlEventTouchUpInside)];
    

//    调到我的信息
    [self.headView.myInfoBT addTarget:self action:@selector(myInfo) forControlEvents:(UIControlEventTouchUpInside)];
    
//    跳到选项设置与设备信息
    [self.headView.optionAndDeviceBT addTarget:self action:@selector(optionAndDevice) forControlEvents:(UIControlEventTouchUpInside)];
//    添加联系人
    [self.headView.addFamilyBT addTarget:self action:@selector(addFamily) forControlEvents:(UIControlEventTouchUpInside)];
//    密码设置
    [self.headView.setPasswordBT addTarget:self action:@selector(passwordSet) forControlEvents:(UIControlEventTouchUpInside)];
//    解除绑定设备
    [self.headView.freeDeviceBT addTarget:self action:@selector(freeDevice) forControlEvents:(UIControlEventTouchUpInside)];
//  系统更新
    [self.headView.sysUpdate addTarget:self action:@selector(sysUpdate) forControlEvents:(UIControlEventTouchUpInside)];
//    换肤
    [self.headView.changeSkinBT addTarget:self action:@selector(changeSkin) forControlEvents:(UIControlEventTouchUpInside)];
//    self.view.backgroundColor = [UIColor colorWithRed:220.0/225 green:220.0/255 blue:220.0/255 alpha:1];
    [self.view addSubview:_headView];
}
// 返回上一个 界面
- (void)back{
    NSLog(@"返回上一个界面");
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 一键上传
- (void)passData{
    
    _isUploading = YES;
//    获取绑定绑定设备的UUID
    if (_uuidString == nil || _uuidString.length < 1) {
        [PKRequestManager showAlertView:@"尚无绑定设备"];
    } else {
        
//        判断设置的是WiFi上传 还是 所有网络上传 先得到当前网络状态
        NSString *netValue = [BSUserSGton userHandle].netstatus;
        
        if ([[[NSUserDefaults standardUserDefaults]stringForKey:@"AllNet"] isEqualToString:@"YES"]) {
            //    弹出提示框 提示剩余的 要显示的数量 所有网络 只要有网就上传
            if (![netValue isEqualToString:@"NoNet"]) {
                [self passDataNote];
                [self uploadDataSet];

            }else{
            
                [PKRequestManager showAlertView:@"网络连接失败"];
            }
         
        } else {
            // 仅WiFi上传
            if ([netValue isEqualToString:@"WIFI"]) {
                [self passDataNote];
                [self uploadDataSet];

            }else{
                [PKRequestManager showAlertView:@"当前网络非WiFi"];
            
            }
            
        }
        
         }
}

- (void)uploadDataSet{
    

    //    管理文件
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *path = @"/ECGData";
    
    NSString *filePath = [documents[0] stringByAppendingString:path];
    
    NSString *zipFile = [filePath stringByAppendingPathComponent:@"/20160510103203.zip"];
    BOOL isExist = [filemanager removeItemAtPath:zipFile error:nil];
    NSLog(@"%d",isExist);
    
    
    NSArray *listArrfile = [BSUserSGton getECGDataFileListFromPath:filePath];
    NSMutableArray *listArr = [NSMutableArray arrayWithArray:listArrfile];

    NSInteger countOffiles = listArrfile.count;

    
    NSString *user_id = [BSUserSGton userHandle].user_id;
    NSArray *arr = [[NSArray alloc]init];
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFile];
    //    [za addFileToZip:sourcePath5 newname:@"20160510103209.dat"];
    
    if (listArr == 0) {
        _isUploading = NO;
        return;
    }
    
    if (listArr.count > 5) {
        arr = [listArr subarrayWithRange:NSMakeRange(0, 5)];
    }else{
        arr = listArr;
    }
    for (int i = 0; i < arr.count; i++) {
        
        NSString *ECGfile = [filePath stringByAppendingPathComponent:arr[i]];
        //        判断这个文件是否为空 为空 直接删除
        long  long int bytes = [[filemanager attributesOfItemAtPath:ECGfile error:nil] fileSize];
        NSLog(@"%lld",bytes);
        
        
        [za addFileToZip:ECGfile newname:arr[i]];
    }
    BOOL success = [za CloseZipFile2];
    NSLog(@"Zipped file with result %d",success);
    
    //    如果压缩成功 打包data  上传
    NSData *filedata = [NSData data];
    if (success) {
        
        NSURL *url2 = [NSURL fileURLWithPath:zipFile];
        
        filedata = [NSData dataWithContentsOfURL:url2];
        [filemanager removeItemAtPath:zipFile error:nil];
    }
    [PKRequestManager ChangePwdWithnetUrl:NetStr upLoadWay:(NSString *)@"2" userID:user_id deviceID:(NSString *)self.uuidString filenames:arr data:filedata method:POST finish:^(NSData *data) {
        //            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        //            NSLog(@"%@",dic);
        //            上传成功 删除 从listArr arr  本地删除arr的文件  修改显示
        StringResponse *model = [[StringResponse alloc]init];
        [model dealNoNoteWithData:data];
        if ([model.Code isEqualToString:@"0"]) {
            for (int i = 0; i < arr.count; i++) {
                
                NSString *ECGfile = [filePath stringByAppendingPathComponent:arr[i]];
                //        判断这个文件是否为空 为空 直接删除
                [filemanager removeItemAtPath:ECGfile error:nil];
                
                NSLog(@"上传成功");
                [listArr removeObject:arr[i]];
                _lableUploadNote.text = [NSString stringWithFormat:@"正在上传%u/%d个",_numberOffiles - (int)listArr.count,_numberOffiles];

                if (listArr.count == 0) {
                    [_uploadButton setTitle:@"已完成" forState:(UIControlStateNormal)];
                    return;
                }
            }
            if (arr.count != 0) {
                 [self uploadDataSet];
            }
           
        } else {
            [PKRequestManager showAlertView:model.Message];
            _isUploading = NO;
        }
    } error:^(NSError *error) {
        ;
    }];

}
- (void)uploadData{
    //    是否持续进行上传

}





- (void)passDataNote{
    NSString *path = [BSBluetoothSingleton shareBlutooth].filePath;
    
    NSArray *listArr = [BSUserSGton getECGDataFileListFromPath:path];
    _numberOffiles = (int)listArr.count;
        [self.view addSubview:_NCview];
        
        _passDataNoteView  = [[UIView alloc]initWithFrame:CGRectMake(kScrenWidth/8, kScrenHeight/2 - kMartin80, kScrenWidth*3/4, 44 *4 - 1)];
        _passDataNoteView.backgroundColor = BSBackColor;
        _passDataNoteView.layer.cornerRadius  = 8;
        CGFloat W = _passDataNoteView.width;
    
    UILabel * noteLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, W - 20, 44)];
    noteLable.text = [NSString stringWithFormat:@"一键上传"];
    noteLable.textAlignment = NSTextAlignmentCenter;
    
    UILabel *lable1 = [[UILabel alloc]initWithFrame:CGRectMake(0, noteLable.bottom, W, 0.5)];
    lable1.backgroundColor = BSGray;
    
    
    
    
    _passdataLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, W - 20, 44)];
    _passdataLable.text = [NSString stringWithFormat:@"当前有待上传:%d个",_numberOffiles];
    _passdataLable.textAlignment = NSTextAlignmentCenter;
    UILabel *lable2 = [[UILabel alloc]initWithFrame:CGRectMake(0, _passdataLable.bottom, W, 0.5)];
    [_passDataNoteView addSubview:noteLable];
    [_passDataNoteView addSubview:_passdataLable];
    [_passDataNoteView addSubview:lable1];
    [_passDataNoteView addSubview:lable2];

    [self.view addSubview:_passDataNoteView];
    
//    正在上传 请稍后
    _lableUploadNote = [[UILabel alloc]initWithFrame:CGRectMake(10, _passdataLable.bottom, W - 20, 44)];
    _lableUploadNote.text = [NSString stringWithFormat:@"正在上传0/%d个",_numberOffiles];
    _lableUploadNote.textAlignment = NSTextAlignmentCenter;
    
    [_passDataNoteView addSubview:_lableUploadNote];
    
    
//    确定的按钮
    _uploadButton = BSButton;
    _uploadButton.frame = CGRectMake((W - 60)/2, _lableUploadNote.bottom + kMartin5,  kMartin50 + kMartin20, 43 - 10) ;
    _uploadButton.layer.cornerRadius = 10;
    _uploadButton.backgroundColor = BSBTGreen;
    [_uploadButton addTarget:self action:@selector(selectYES:) forControlEvents:(UIControlEventTouchUpInside)];
    [_passDataNoteView addSubview:_uploadButton];
    [_uploadButton setTitle:@"停止" forState:(UIControlStateNormal)];
    
}
- (void)selectYES:(UIButton *)button{
    _isUploading = NO;
    [_NCview removeFromSuperview];
    [_passDataNoteView removeFromSuperview];

}

//我的信息
- (void)myInfo{
    BSMyInfoViewController *myVC = [[BSMyInfoViewController alloc]init];
    myVC.user_id = self.user_id;

    [self.navigationController pushViewController:myVC animated:YES];

}
//选项设置与设备信息
- (void)optionAndDevice{

    BSOptionAndDeviceInfoViewController *opdeVC = [[BSOptionAndDeviceInfoViewController alloc]init];
    [self.navigationController pushViewController:opdeVC animated:YES];
    
}
//添加联系人
- (void)addFamily{

    BSAddFanmilyViewController *addVC = [[BSAddFanmilyViewController alloc]init];
    addVC.user_id = self.user_id;
    [self.navigationController pushViewController:addVC animated:YES];
    

}

- (void)passwordSet{

    BSPasswordSettingViewController *passwordSetVC = [[BSPasswordSettingViewController alloc]init];
    [self.navigationController pushViewController:passwordSetVC animated:YES];
}

// 系统更新
- (void)sysUpdate{

    [PKRequestManager showAlertView:@"当前已是最新版本"];
}

//换肤
- (void)changeSkin{
//    [PKRequestManager showAlertView:@"尚无最终需求" ];
}

// 解除绑定设备
- (void)freeDevice{
    if (self.uuidString == nil || self.uuidString.length < 2) {
        [PKRequestManager showAlertView:@"尚无绑定设备"];
        return;
    }
    
    
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否解除绑定?" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
        //       先看你 是不是有绑定的设备
        [PKRequestManager GetUserDeviceWithuserID:[BSUserSGton userHandle].user_id method:POST finish:^(NSData *data) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            BSUIDeviceResponseList *model = [[BSUIDeviceResponseList alloc]init];

            [model dealWithData:data];
            
            if ([model.Code isEqualToString:@"0"]) {
                self.uuidString = model.DeviceModel.UUID;
//                有这个UUID 就可以 接收验证码
                [PKRequestManager GetFreeDeviceVerifyWithuserID:[BSUserSGton userHandle].user_id iDCode:_uuidString method:POST finish:^(NSData *data) {
                    StringResponse *model = [[StringResponse alloc]init];
                    [model dealNoNoteWithData:data];
                    
                    if ([model.Code isEqualToString:@"0"]) {
                        [self freeDeviceView];
                    } else {
                        [PKRequestManager showAlertView:model.Message];
                    }
                    
                    
                    
                } string:NetStr error:^(NSError *error) {
                    ;
                }];
                
                
                
                
            } else {
                [PKRequestManager showAlertView:model.Message];
            }
            
            ;
        } string:NetStr error:^(NSError *error) {
            ;
        }];

    }];
    
    UIAlertAction *setAcion = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
       


        
    }];
    [alert addAction:cancleAction];
    [alert addAction:setAcion];
    
    [self presentViewController:alert animated:YES completion:^{
        nil;
    }];
    
    
}
- (void)freeDeviceView{
    _NCview = [[UIView alloc]initWithFrame:self.view.bounds];
    _NCview.backgroundColor = BSBackViewColor;
    _NCview.alpha = 0.5;
    [self.view addSubview:_NCview];
    
    _freeLableView  = [[BSUIView alloc]initWithFrame:CGRectMake(kScrenWidth/8, kScrenHeight/2 - kMartin80, kScrenWidth*3/4, 44 *6 - 22)];
    _freeLableView.backgroundColor = BSWhite;
    _freeLableView.layer.cornerRadius  = 3;
    
    CGFloat W = _freeLableView.width;
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, W , 43)];
    titleLable.layer.cornerRadius = 3;
    titleLable.text = @"解除绑定";
    titleLable.backgroundColor = BSBackColor;
    titleLable.textAlignment = NSTextAlignmentCenter;
    [_freeLableView addSubview:titleLable];
    
    UILabel *noteLable = [[UILabel alloc]initWithFrame:CGRectMake(0, titleLable.bottom, W/3, 43)];
    noteLable.text = @"    验证码:";
    noteLable.backgroundColor = BSWhite;
    [_freeLableView addSubview:noteLable];
    _freeTextfeild = [[UITextField alloc]initWithFrame:CGRectMake(noteLable.right - 1, noteLable.top , W/3 * 2 - 1, 43)];
    _freeTextfeild.backgroundColor = BSWhite;
    _freeTextfeild.tag = 501;
    _freeTextfeild.delegate = self;
    _freeTextfeild.placeholder = @"请输入短信验证码";
    
    UILabel *lable2 = [[UILabel alloc]initWithFrame:CGRectMake(0, _freeTextfeild.bottom + 1, W, 43)];
    lable2.text = @"    是否解除绑定?";
    
//    lable2.backgroundColor = BSWhite;
    [_freeLableView addSubview:lable2];
    
    
    //    确定 和 取消   按钮
    
    //    按钮的宽度
    CGFloat bw = W / 4;
    
    UIButton *confirmBT = BSButton;
    confirmBT.frame = CGRectMake(bw *3/5, lable2.bottom + kMartin15, bw + kMartin10, bw/2);
    [confirmBT setTitle:@"确定" forState:(UIControlStateNormal)];
    confirmBT.backgroundColor = BSBTGreen;
    [confirmBT addTarget:self action:@selector(conform:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    UIButton *cancleBT = BSButton;
    cancleBT.frame = CGRectMake(W - confirmBT.width - confirmBT.left, confirmBT.top,  bw + kMartin10, bw/2);
    [cancleBT setTitle:@"取消" forState:(UIControlStateNormal)];
    cancleBT.backgroundColor = BSGray;
    [cancleBT addTarget:self action:@selector(cancelS:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    confirmBT.layer.cornerRadius = 3;
    cancleBT.layer.cornerRadius = 3;
    [_freeLableView addSubview:confirmBT];
    [_freeLableView addSubview:cancleBT];
    [_freeLableView addSubview:_freeTextfeild];
    

//    notelable3
    UILabel *lable3 = [[UILabel alloc]initWithFrame:CGRectMake(0, confirmBT.bottom + kMartin15, W, kMartin25)];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString: @"  *您也可以通过拨打000-123456789客服电话进行解绑"];
    lable3.numberOfLines = 0;

    [str addAttribute:NSForegroundColorAttributeName value:BSRed range:NSMakeRange(2,1)];
    lable3.attributedText = str;
    lable3.font = [UIFont systemFontOfSize:10];
    lable3.backgroundColor = BSBackColor;
    [_freeLableView addSubview:lable3];

    [self.view addSubview:_freeLableView];


}
- (void)conform:(UIButton *)sender{

    [PKRequestManager FreeDeviceWithuserID:[BSUserSGton userHandle].user_id iDCode:_uuidString verifyCode:self.freeTextfeild.text method:POST finish:^(NSData *data) {
        StringResponse *model = [[StringResponse alloc]init];
        [model dealWithData:data];
        if ([model.Code isEqualToString:@"0"]) {
//            [PKRequestManager showAlertView:@"解绑成功"];
//            断开连接链接 链接状态设置no
            [[BSBluetoothSingleton shareBlutooth].manager cancelPeripheralConnection: [BSBluetoothSingleton shareBlutooth].perpheral];
            [BSBluetoothSingleton shareBlutooth].isConnected = NO;
            
            
            [BSBluetoothSingleton shareBlutooth].uuiduuid = nil;
            [BSUserSGton userHandle].identifire = nil;
            [_NCview removeFromSuperview];
            [_freeLableView removeFromSuperview];
            
            
        } else {
            [PKRequestManager showAlertView:model.Message];
        }
    } string:NetStr error:^(NSError *error) {
        ;
    }];

    
    
}
- (void)cancelS:(UIButton *)sender{

    [_NCview removeFromSuperview];
    [_freeLableView removeFromSuperview];
    
}

- (void)addTableview{

    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 172, kScreenWidth, kScreenHeight) style:(UITableViewStyleGrouped)];
    self.tableview.delegate = self;
    self.tableview.rowHeight = 86;
    self.tableview.dataSource = self;
    [self.view addSubview:_tableview];

}

//tableview 的三个代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"MyCell";
    BSSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[BSSettingTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    return cell;
    
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];
    return YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
